<?php
namespace app\common\model;

use think\Model;
use think\facade\Db;
/**
 * @package Home\Model
 */
class Order extends Model
{
    public $payname='订单支付';
    protected $pk = 'order_id';
    //获取所有订单商品
    public function OrderGoods()
    {
        return $this->hasMany('OrderGoods','order_id','order_id')->field('*');
    }

    /**
     * 订单详细收货地址
     * @param $value
     * @param $data
     * @return string
     */
    public function getFullAddressAttr($value, $data)
    {
        $province =  Region::where(['id'=>$data['province']])->value('name');
        $city = Region::where(['id'=>$data['city']])->value('name');
        $district =Region::where(['id'=>$data['district']])->value('name');
        $adderss = $province.'，'.$city.'，'.$district.'，'.$data['address'];
        return $adderss;
    }

    /**
     * 支付前
     */
    public function beforePay($ids){

    }

    /**
     * 支付后
     */
    public function afterPay($id){

        $curtime = getCurTime();
        //更新产品订单状态
        $rs = Db::name('order_goods')->whereIn('order_id',$id)->update(['order_status'=>1,'pay_time'=>$curtime]);
        if(!$rs){
            return ['status'=>0,'msg'=>'更新产品订单状态失败'];
        }

        //更新产品销售
        $goods = Db::name('order_goods')->whereIn('order_id',$id)->select();
        foreach($goods as $v){
            $rs = Db::name('goods')->whereIn('goods_id',$v['goods_id'])->inc('sales_sum',$v['real_num'])->update();
            if(!$rs){
                return ['status'=>0,'msg'=>'更新产品销量失败'];
            }
        }


        $order = Db::name('order')->where(['order_id'=>$id])->find();
        if($order['use_score']>0 && $order['pay_score']>0){
            qianbao($order['user_id'],$order['pay_score']*-1,'score','订单抵扣','订单'.$id.'购物消费积分抵扣');
        }

        //升级处理
        $res = logic('UsersLogic')->uplv($order);
        if(!$res['status']){
            //return $res;
        }
        if(!empty($order['reward_score'])){
            //赠送积分
            $res = qianbao($order['user_id'],$order['reward_score'],'score','购物赠送积分','订单'.$id.'购物赠送积分');
        }

        return ['status'=>1];
    }
}